class Chunk {
	constructor(id, offset, size, targetSize) {
		this.id = id;
		this.offset = offset;
		this.size = size;
		this.targetSize = targetSize;
	}
}

export default class Bundle {
	constructor(id) {
		this.id = id;
		/** @type {Chunk[]} */
		this.chunks = [];
	}

	addChunk(id, size, targetSize) {
		const lastChunk = this.chunks[this.chunks.length - 1];

		this.chunks.push(
			new Chunk(id, (lastChunk ? lastChunk.offset + lastChunk.size : 0), size, targetSize)
		);
	}

	static parse(biffer) {
		const [, sizeHeader, id] = biffer.unpack('<llQ');

		// Skip remaining header part
		biffer.skip(sizeHeader - 12);

		const bundle = new Bundle(id);

		const [sizeChunk] = biffer.unpack('<l');
		for(let i = 0; i < sizeChunk; i++) {
			const pos = biffer.tell();
			const [offset] = biffer.unpack('<l');

			biffer.seek(pos + offset);
			biffer.skip(4); // skip offset table offset

			const [sizeCompressed, sizeUncompressed, idChunk] = biffer.unpack('<LLQ');

			bundle.addChunk(idChunk, sizeCompressed, sizeUncompressed);

			biffer.seek(pos + 4);
		}

		return bundle;
	}
}